/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.sesame.domain.Admin;
import com.sesame.domain.User;
import com.sesame.service.AdminService;
import com.sesame.service.UserService;

/**
 * @author voidman
 * 
 */
public class NewAdminController extends SimpleFormController {

    private AdminService adminService;

    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        if ("root".equals(request.getSession().getAttribute("adminRank"))) {
            String confirmPassword = request.getParameter("confirmPassword");
            Admin admin = (Admin) command;

            Date createTime = new Date();
            admin.setCreateTime(createTime);
            admin.setRank("admin"); // admin表示为普通管理员

            Map model = errors.getModel();

            boolean isRightPassword = adminService.validatePassword(admin,
                    confirmPassword, model);
            boolean isNewAdmin = false;

            if (isRightPassword) {
                isNewAdmin = adminService.isNewAdmin(admin, model);
            }

            if (isNewAdmin) {
                return new ModelAndView("redirect:adminList.html");
            } else {
                return new ModelAndView(getFormView(), model);
            }
        } else {
            return new ModelAndView("redirect:adminError.html");
        }

    }

}